<?php

use Drupal\shusy_store\Entity\ShusyStore;

function shusy_store_stats_page() {
  global $user;
  $store = shusy_store_bind_load_by_uid($user->uid);
  if ($store instanceof ShusyStore) {
    $query = db_select('shusy_store_stats', 's');
    $query->fields('s', ['id', 'type', 'number']);
    $query->condition('store_id', $store->id);
    $inday = strtotime(format_date(REQUEST_TIME, 'custom', 'Y-m-d'));
    $query->condition('inday', $inday);
    $result = $query->execute();
    $order = 0;
    $view = 0;
    $follow = 0;
    $refund = 0;
    while ($row = $result->fetchAssoc()) {
      switch ($row['type']) {
        case 'order':
          $order = $row['number'];
          break;
        case 'view':
          $view = $row['number'];
          break;
        case 'follow':
          $follow = $row['number'];
          break;
        case 'refund':
          $refund = $row['number'];
          break;
      }
    }
    /**
     * 'order' => '订单量',
     * 'view' => '浏览量',
     * 'follow' => '关注数',
     * 'refund' => '退单数',
     */
    $stats = [
      'order' => $order,
      'view' => $view,
      'follow' => $follow,
      'refund' => $refund,
      'date' => format_date($inday, 'custom', 'Y-m-d'),
    ];
    return theme('shusy_store_stats', [
      'store' => $store,
      'stats' => $stats,
    ]);
  }
  return '当前用户未绑定店铺!';
}

function shusy_store_stats_store_page(ShusyStore $store) {
  $query = db_select('shusy_store_stats', 's');
  $query->fields('s', ['id', 'type', 'number']);
  $query->condition('store_id', $store->id);
  $inday = strtotime(format_date(REQUEST_TIME, 'custom', 'Y-m-d'));
  $query->condition('inday', $inday);
  $result = $query->execute();
  $order = 0;
  $view = 0;
  $follow = 0;
  $refund = 0;
  while ($row = $result->fetchAssoc()) {
    switch ($row['type']) {
      case 'order':
        $order = $row['number'];
        break;
      case 'view':
        $view = $row['number'];
        break;
      case 'follow':
        $follow = $row['number'];
        break;
      case 'refund':
        $refund = $row['number'];
        break;
    }
  }
  /**
   * 'order' => '订单量',
   * 'view' => '浏览量',
   * 'follow' => '关注数',
   * 'refund' => '退单数',
   */
  $stats = [
    'order' => $order,
    'view' => $view,
    'follow' => $follow,
    'refund' => $refund,
    'date' => format_date($inday, 'custom', 'Y-m-d'),
  ];
  return theme('shusy_store_stats', [
    'store' => $store,
    'stats' => $stats,
  ]);
}
